<?php

namespace App\Http\Controllers\Admin\Dispatch;

use App\Http\Controllers\Admin\Examine\Record;
use App\Http\Controllers\Controller;
use App\Http\Requests\dispatch\PurchaseRequest;
use App\Imports\OfficeImport;
use App\Imports\PurchaseImport;
use App\Models\administration\OfficeModel;
use App\Models\dispatch\PurchaseDetailModel;
use App\Models\dispatch\PurchaseModel;
use App\Models\dispatch\StockModel;
use App\Models\dispatch\StockRecordModel;
use App\Models\examine\ConfigModel;
use App\Models\examine\RecordDetailModel;
use App\Models\examine\RecordModel;
use App\Models\StaffModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Facades\Excel;

class Purchase extends Controller
{
    use PurchaseRequest;

    /**
     * Notes:审核列表
     * User: xiangzi
     * Date: 2024/9/5
     * Time: 14:35
     * @return \Illuminate\Http\JsonResponse
     */
    public function examine_list(Request $request) {
        $auth = $request->get('auth');
        $page = $request->input('page', 1);
        $limit = $request->input('limit', 20);
        $name = $request->input('name', '');
        $my_status = $request->input('my_status', '');
        $status = $request->input('status', '');
        $auth_id = $auth->id;


        $query = DB::table('t_examine_record_detail as d')
            ->leftJoin('t_examine_record as e', 'e.id', '=', 'd.record_id')
            ->leftJoin('t_dispatch_material_purchase as p', 'p.examine_record_id', '=', 'e.id')
            ->leftJoin('t_dispatch_material as m', 'm.id', '=', 'p.material_id')
            ->leftJoin('t_admin as a', 'a.id', '=', 'd.admin_id')
            ->leftJoin('t_staff as s', 's.id', '=', 'a.staff_id')
            ->where('d.admin_id', $auth->id)
            ->where('d.type', 6);


//        $query = PurchaseModel::with('create_admin')
//            ->withWhereHas('material', function ($query) use ($name) {
//                if($name){
//                    $query->where('name', 'like', '%' . $name . '%');
//                }
//            })
//            ->withWhereHas('record', function ($query) use ($status, $my_status, $auth_id) {
//                $where = [];
//                if($status){
//                    $where[] = ['status', '=', $status];
//                }
//                $query->withWhereHas('detail', function ($query) use ($my_status, $auth_id){
//                    $where = [];
//                    if($my_status){
//                        $where[] = ['status', '=', $my_status];
//                    }
//                    $query->where($where)->where('staff_id', $auth_id);
//                })->where($where);
//            });
//
//        $items = $query->get();
//
//        $list = $items->map(function ($item) {
//            $res = [
//                'id' => $item->id,
//                'material_name' => $item->material->name ?? '',
//                'status' => $item->record->status ?? '',
//                'staff_id' => $item->record->detail ? $item->record->detail[0]->staff_id : '',
//            ];
//            return $res;
//        });
//        $total = $query->count('id');
//
//        return $this->success(['list' => $list, 'total' => $total]);

        if($name){
            $query = $query->where('m.name', 'like', '%'.$name.'%');
        }

        if($my_status){
            $query = $query->where('d.status', $my_status);
        }

        if($status){
            $query = $query->where('e.status', $status);
        }

        $total = $query->count('d.id');
        $items = $query
            ->offset(($page-1) * $limit)
            ->limit($limit)
            ->select('e.id', 's.name as create_user', 'm.name as material_name', 'm.code as material_code', 'm.unit as material_unit',
                'm.color  as material_color', 'p.purchase_number', 'd.status as my_status', 'e.status', 'p.created_at', 'd.is_examine')
            ->orderBy('d.id', 'desc')
            ->get();

        $list = $items->map(function($item) {
            $res = [
                'id' => $item->id,
                'create_user' => $item->create_user,
                'material_name' => $item->material_name,
                'material_code' => $item->material_code,
                'material_unit' => $item->material_unit,
                'purchase_number' => $item->purchase_number,
                'material_color' => $item->material_color ?? '',
                'my_status' => $item->my_status,
                'my_status_text' => RecordModel::STATUS[$item->my_status],
                'status' => $item->status,
                'status_text' => RecordModel::STATUS[$item->status],
                'created_at' => $item->created_at,
                'is_examine' => $item->is_examine,
            ];
            return $res;
        });

        return $this->success(['list' => $list, 'total' => $total]);
    }

    /**采购单列表
     * Notes:
     * User: xiangzi
     * Date: 2024/9/14
     * Time: 15:12
     * @return \Illuminate\Http\JsonResponse
     */
    public function purchase_list(Request $request)
    {
        $page = $request->input('page', 1);
        $limit = $request->input('limit', 20);
        $name = $request->input('name', '');
        $status = $request->input('status', '');
        $create_start = $request->input('create_start', '');
        $create_end = $request->input('create_end', '');

        $query = PurchaseModel::with('create_admin')
            ->withWhereHas('material', function ($query) use ($name) {
                if($name){
                    $query->where('name', 'like', '%' . $name . '%');
                }
            })
            ->withWhereHas('record', function ($query) use ($status) {
                if($status){
                    $query->where('status', $status);
                }
            });


        if($create_start && $create_end){
            $query = $query->whereBetween('created_at', [$create_start, $create_end]);
        }

        $total = $query->count('id');
        $items = $query
            ->offset(($page-1) * $limit)
            ->limit($limit)
            ->orderBy('id', 'desc')
            ->get();

        $list = $items->map(function($item) {
            $res = [
                'id' => $item->id,
                'create_user' => $item->create_admin->staff->name ?? '',
                'material_id' => $item->material->id ?? '',
                'material_name' => $item->material->name ?? '',
                'material_code' => $item->material->code ?? '',
                'material_unit' => $item->material->unit ?? '',
                'purchase_number' => $item->purchase_number,
                'remarks' => $item->remarks,
                'status' => $item->status,
                'status_text' => PurchaseModel::STATUS[$item->status],
                'created_at' => $item->created_at->toDateTimeString(),
                'is_storage' => $item->is_storage,
            ];
            return $res;
        });

        return $this->success(['list' => $list, 'total' => $total]);
    }

    /**
     * Notes:添加
     * User: xiangzi
     * Date: 2024/9/5
     * Time: 14:35
     * @return \Illuminate\Http\JsonResponse
     */
    public function add(Request $request){
        $auth = $request->get('auth');
        $params = $request->all();

        $check_res = self::add_check($params);
        if($check_res->faild){
            return $this->error($check_res->err);
        }

        DB::beginTransaction();
        try {
            $model = new PurchaseModel();
            $model->material_id = $params['material_id'];
            $model->purchase_number = $params['purchase_number'];
            $model->spe = $params['spe'] ?? '';
            $model->remarks = isset($params['remarks']) ? $params['remarks'] : '';
            $model->created_admin_id = $auth->id;
            $model->examine_record_id = (new Record())->add(6);
            $model->save();

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->error($e->getMessage());
        }

        return $this->success();
    }

    /**
     * Notes:采购申请
     * User: xiangzi
     * Date: 2025/4/29
     * Time: 下午3:47
     * @return \Illuminate\Http\JsonResponse
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    public function add_old(Request $request){
        $auth = $request->get('auth');
        $params = $request->all();

        if(!$params['data']){
            return $this->error('请填写采购数据');
        }

        DB::beginTransaction();
        try {

            $model = new PurchaseModel();
            $model->code = getCode('purchase', "CG");
            $model->created_admin_id = $auth->id;
            $model->examine_record_id = (new Record())->add(6);
            $model->save();

            foreach ($params['data'] as $item){
                $detail = new PurchaseDetailModel();

                $check_res = self::add_check($item);
                if($check_res->faild){
                    DB::rollBack();
                    return $this->error($check_res->err);
                }

                $detail->purchase_id = $model->id;
                $detail->material_id = $item['material_id'];
                $detail->purchase_number = $item['purchase_number'];
                $detail->spe = isset($item['spe']) ? $item['spe'] : '';
                $detail->remarks = isset($item['remarks']) ? $item['remarks'] : '';
                $detail->save();
            }

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->error($e->getMessage());
        }

        return $this->success();
    }

    public function examine(Request $request, $id){
        $params = $request->all();

        $check_res = self::examine_check($params);
        if($check_res->faild){
            return $this->error($check_res->err);
        }

        $model = RecordDetailModel::find($id);
        if (!$model) {
            return $this->error('数据不存在');
        }

        DB::beginTransaction();
        try {
            $model->status = $params['status'];
            $model->examine_remarks = isset($params['examine_remarks']) ? $params['examine_remarks'] : '';
            $model->examine_time = date('Y-m-d H:i:s');
            $model->save();

            $record = RecordModel::find($model->record_id);
            $purchase = PurchaseModel::where('examine_record_id', $model->record_id)->first();
            if($record->status == 1){
                switch ($record->examine_type) {
                    case 1:
                        $find_next = RecordDetailModel::where('record_id', $model->record_id)->where('is_examine', 0)->orderBy('sort')->first();
                        if($find_next){
                            $find_next->is_examine = 1;
                            $find_next->save();
                        }else{
                            $record->status = $params['status'];
                            $record->save();
                            $purchase->status = $params['status'];
                            $purchase->save();
                        }
                        break;
                    case 2:
                        $record->status = $params['status'];
                        $record->save();
                        $purchase->status = $params['status'];
                        $purchase->save();
                        break;
                    case 3:
                        if($params['status'] == 3){
                            $record->status = $params['status'];
                            $record->save();
                            $purchase->status = $params['status'];
                            $purchase->save();
                        }else if($params['status'] == 2){
                            $find_else = RecordDetailModel::where('record_id', $model->record_id)->where('status', 1)->first();
                            if(!$find_else){
                                $record->status = $params['status'];
                                $record->save();
                                $purchase->status = $params['status'];
                                $purchase->save();
                            }
                        }
                        break;
                    default:
                }
            }
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->error($e->getMessage());
        }

        return $this->success();
    }

    /**
     * Notes:采购单详情
     * User: xiangzi
     * Date: 2024/9/14
     * Time: 13:54
     * @return \Illuminate\Http\JsonResponse
     */
    public function detail(Request $request, $id){
        $auth = $request->get('auth');

        $purchase_info = PurchaseModel::with(['material', 'create_admin'])->find($id);
        if(!$purchase_info){
            return $this->error('记录不存在');
        }

        $record_id = $purchase_info->examine_record_id;
        $record = RecordModel::find($record_id);
        if(!$record) {
            return $this->error('审核记录不存在');
        }

        $record_detail = RecordDetailModel::where('record_id', $record_id)->where('admin_id', $auth->id)->first();

        $return = [
            'base_info' => [
                'apply_user' => $purchase_info->create_admin->staff->name ?? '',
                'material_name' => $purchase_info->material ? $purchase_info->material->name : '',
                'purchase_number' => $purchase_info->purchase_number,
                'apply_time' => $purchase_info->created_at->toDateTimeString(),
                'my_status' => PurchaseModel::STATUS[$record_detail->status],
                'status' => PurchaseModel::STATUS[$record->status],
            ],
            'examine_info' => [
                'examine_type' => ConfigModel::EXAMINE_TYPE[$record->examine_type],
                'examine_list' => (new Record())->examine_info($record_id)
            ]
        ];

        if($purchase_info->file){
            $return['file'] = json_decode($purchase_info->file, true);
        }

        return $this->success($return);
    }

    /**
     * Notes:审批详情
     * User: xiangzi
     * Date: 2024/9/14
     * Time: 13:54
     * @return \Illuminate\Http\JsonResponse
     */
    public function examine_detail(Request $request, $id){
        $auth = $request->get('auth');

        $purchase_info = PurchaseModel::with(['material', 'create_admin'])->where('examine_record_id', $id)->first();
        if(!$purchase_info){
            return $this->error('记录不存在');
        }

        $record_id = $purchase_info->examine_record_id;
        $record = RecordModel::find($record_id);
        if(!$record) {
            return $this->error('审核记录不存在');
        }

        $record_detail = RecordDetailModel::where('record_id', $record_id)->where('admin_id', $auth->id)->first();

        $return = [
            'base_info' => [
                'apply_user' => $purchase_info->create_admin->staff->name ?? '',
                'material_name' => $purchase_info->material ? $purchase_info->material->name : '',
                'purchase_number' => $purchase_info->purchase_number,
                'apply_time' => $purchase_info->created_at->toDateTimeString(),
                'my_status' => PurchaseModel::STATUS[$record_detail->status],
                'status' => PurchaseModel::STATUS[$record->status],
            ],
            'examine_info' => [
                'examine_type' => ConfigModel::EXAMINE_TYPE[$record->examine_type],
                'examine_list' => (new Record())->examine_info($record_id)
            ]
        ];

        if($purchase_info->file){
            $return['file'] = json_decode($purchase_info->file, true);
        }

        return $this->success($return);
    }

    /**
     * Notes:上传资料凭证
     * User: xiangzi
     * Date: 2024/9/14
     * Time: 14:55
     * @return \Illuminate\Http\JsonResponse
     */
    public function file(Request $request, $id){
        $params = $request->all();

        $check_res = self::file_check($params);
        if($check_res->faild){
            return $this->error($check_res->err);
        }

        $model = PurchaseModel::find($id);
        if (!$model) {
            return $this->error('数据不存在');
        }

        $model->file = json_encode($params['file']);
        $model->save();

        return $this->success();
    }

    /**
     * Notes:取消采购
     * User: xiangzi
     * Date: 2024/9/14
     * Time: 15:15
     * @return \Illuminate\Http\JsonResponse
     */
    public function cancel(Request $request, $id){
        $model = PurchaseModel::find($id);
        if (!$model) {
            return $this->error('数据不存在');
        }

        $model->status = 4;
        $model->cancel_time = date('Y-m-d H:i:s');
        $model->save();
        return $this->success();
    }

    /**
     * Notes:确认采购
     * User: xiangzi
     * Date: 2024/9/14
     * Time: 15:15
     * @return \Illuminate\Http\JsonResponse
     */
    public function confirm(Request $request, $id){
        $model = PurchaseModel::find($id);
        if (!$model) {
            return $this->error('数据不存在');
        }

        $model->status = 5;
        $model->confirm_time = date('Y-m-d H:i:s');
        $model->save();
        return $this->success();
    }

    /**
     * Notes:编辑
     * User: xiangzi
     * Date: 2024/9/27
     * Time: 16:44
     * @return \Illuminate\Http\JsonResponse
     */
    public function update(Request $request, $id){
        $params = $request->all();

        $check_res = self::add_check($params);
        if($check_res->faild){
            return $this->error($check_res->err);
        }

        $model = PurchaseModel::find($id);
        if (!$model) {
            return $this->error('数据不存在');
        }

        $model->purchase_number = $params['purchase_number'];
        $model->remarks = $params['remarks'] ?? '';
        $model->save();

        return $this->success();
    }

    /**
     * Notes:采购审核流程
     * User: xiangzi
     * Date: 2024/9/27
     * Time: 17:00
     * @return \Illuminate\Http\JsonResponse
     */
    public function examine_info()
    {
        $config = ConfigModel::where('type', 6)->first();
        $return['examine_type'] = ConfigModel::EXAMINE_TYPE[$config->examine_type] ?? '';

        $examine_staff_id = json_decode($config->examine_staff_id, true);

        foreach ($examine_staff_id as $key => $value) {
            $staff_info = StaffModel::with('role')->find($value['staff_id']);
            $return['examine_list'][] = [
                'staff_name' => $staff_info->name,
                'staff_role' => $staff_info->role ? $staff_info->role->name : '',
            ];
        }

        return $this->success($return);
    }

    /**
     * Notes:一键入库
     * User: xiangzi
     * Date: 2025/4/24
     * Time: 上午11:49
     * @return \Illuminate\Http\JsonResponse
     */
    public function storage(Request $request, $id){
        $model = PurchaseModel::find($id);
        $auth = $request->get('auth');

        if (!$model) {
            return $this->error('采购单不存在');
        }

        $find = PurchaseModel::where('id', $model->id)->get();

        DB::beginTransaction();
        try {
                $find->is_storage = 1;
                $find->save();

                $stock = StockModel::where('material_id', $find->material_id)->first();
                $stock->stock_number += $find->purchase_number;
                $stock->save();

                $record = new StockRecordModel();
                $record->material_id = $find->material_id;
                $record->number = $find->purchase_number;
                $record->type = 1;
                $record->created_admin_id = $auth->id;
                $record->save();


            DB::commit();
        }catch (\Exception $e) {
            DB::rollBack();
            return $this->error($e->getMessage());
        }

        return $this->success();
    }

    /**
     * Notes:导入
     * User: xiangzi
     * Date: 2025/4/29
     * Time: 上午11:49
     * @return \Illuminate\Http\JsonResponse
     */
    public function import(Request $request)
    {
        $auth = $request->get('auth');
        $file = $request->file('file');
        if(!$file){
            return $this->error('请选择文件');
        }

        $import = new PurchaseImport();
        Excel::import($import, $file);


        $res = $import->get_result();

        if(isset($res->error) && $res->error){
            return $this->error(implode(',', $res->error));
        }

        $lines = $res->lines;

        DB::beginTransaction();
        try {
            foreach ($lines as $line){
                $staff = new PurchaseModel();
                foreach ($line as $k => $v){
                    $staff->$k = $v;
                }
                $staff->created_admin_id = $auth->id;
                $staff->save();
            }
            DB::commit();
        }catch (\Exception $e){
            DB::rollBack();
            return $this->error($e->getMessage());
        }

        return  $this->success();
    }

}
